package com.example.competitionregistration.controller;

import com.example.competitionregistration.common.ErrorCode;
import com.example.competitionregistration.common.Result;
import com.example.competitionregistration.entity.Attachement;
import com.example.competitionregistration.service.impl.AttachementServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @Author ZhangJun
 * @Description //附件上传下载的控制层
 * @Date 2023/7/20
 **/
@RestController
@RequestMapping("/Attachement/")
@MapperScan("com.example.competitionregistration.mapper")
public class AttachementController {
    @Resource
    private AttachementServiceImpl attachementService;

    @PostMapping("upload")
    public Result upload(@RequestParam("userId") String userId, @RequestParam("file") MultipartFile file) {
        return attachementService.uploadFile(userId, file);
    }

    @GetMapping("download")
    public Result download(@RequestParam("file") String fileUuid, HttpServletResponse response) {
        try {
            Result result = attachementService.getFile(fileUuid);
            if (result.getCode() != Result.success().getCode()) {
                return result;
            } else {
                Attachement file = (Attachement) result.getData();
                response.setContentType("application/force-download");
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getFileName(), StandardCharsets.UTF_8));
                IOUtils.copy(new FileInputStream(attachementService.getActualPath(file)), response.getOutputStream());
                response.flushBuffer();
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            response.reset();
            return Result.error(ErrorCode.FILE_IO_EXCEPTION_ERROR.getCode(), ErrorCode.FILE_IO_EXCEPTION_ERROR.getMsg());
        }
    }
}
